import { DictionaryType, requestDict } from '../../../common/dictionary/dictionary-type.js';

(function (window, document, $) {
    let _vm,
        savetype,
        getEntryInfo = [];
    $(function () {
        _vm = new Vue({
            el: '#saleordersentry-form',
            data() {
                return {
                    entries: [
                        {
                            id: '',
                            requrchaseLevel: '',
                            specLevel: '',
                            weight: '',
                            avgWeight: '',
                            price: '',
                            isSettlementQty: false,
                            count: '',
                            amount: '',
                            carNo: '',
                            avgWeightShow: '',
                            amountShow: '',
                        },
                    ],
                    uploadCount: 0,
                };
            },
            mounted() {
                let url = location.href;
                let params = {}; // url参数
                for (let key of new URL(url).searchParams.entries()) {
                    key[1] ? (params[key[0]] = key[1]) : '';
                }
                if (params.isEdit == 'true') {
                    document.title = '猪只回购单分录 - 编辑';
                }
            },
            methods: {
                submit() {
                    if (!Utils.IsNotNull(_vm.entries[0]?.requrchaseLevel)) {
                        return $.toptip(`请选择回购品级!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0]?.specLevel)) {
                        return $.toptip(`请选择销售品类!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0]?.weight)) {
                        return $.toptip(`请输入重量!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0]?.count)) {
                        return $.toptip(`请输入数量!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0]?.price)) {
                        return $.toptip(`请输入回购单价!`, 'warning');
                    }
                    if (!Utils.IsNotNull(_vm.entries[0]?.carNo)) {
                        return $.toptip(`请输入运输车牌!`, 'warning');
                    }

                    var reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
                    if (!reg.test(_vm.entries[0].weight)) return $.toptip(`重量必须大于0并且只能保留两位小数`, 'warning');

                    if (!/(^[1-9]\d*$)/.test(_vm.entries[0].count)) {
                        return $.toptip(`数量必须为大于0的整数!`, 'warning');
                    }
                    // if (!reg.test(_vm.entries[0].price)) return $.toptip(`回购单价必须大于0并且只能保留两位小数`, 'warning');

                    const LICENSE_PLATE = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
                    if (!LICENSE_PLATE.test(_vm.entries[0].carNo)) return $.toptip(`请输入正确的车牌`, 'warning');

                    savetips({ ..._vm.entries[0] });
                },
            },
        });

        _initCommand();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = async () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../pigrepurchases/addpigrepurchases.html?v=${Utils.GetTime()}`;
        });

        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage('getEntryInfo')) || [];
        let isEdit = JSON.parse(getUrlKey('isEdit'));
        let id = getUrlKey('index');

        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find((item) => item.id == id);
            _vm.entries[0].id = datas?.id;
            _vm.entries[0].requrchaseLevel = datas?.requrchaseLevel;
            _vm.entries[0].specLevel = datas?.specLevel;
            _vm.entries[0].weight = datas?.weight;
            _vm.entries[0].avgWeight = Number(datas?.avgWeight).toFixed(2);
            _vm.entries[0].avgWeightShow = Utils.toThousands(datas?.avgWeight, 2);

            _vm.entries[0].price = datas?.price;
            _vm.entries[0].isSettlementQty = datas?.isSettlementQty;
            _vm.entries[0].count = datas?.count;
            _vm.entries[0].amount = Number(datas?.amount).toFixed(2);
            _vm.entries[0].amountShow = Utils.toThousands(datas?.amount, 2);
            _vm.entries[0].carNo = datas?.carNo;
        }

        // 初始化 回购品级
        let type = await requestDict(DictionaryType.PIGREQURCHASELEVEL_TYPE);
        let remedyDate = type.data;
        $('#requrchaseLevel')
            .empty()
            .select2({
                placeholder: '请选择回购品级...', //默认文字提示
                language: 'zh-CN', //汉化
                allowClear: true, //允许清空
                data: remedyDate.map((item) => {
                    return {
                        id: item.value,
                        text: item.displayName,
                    };
                }),
            });
        $('#requrchaseLevel').on('select2:select', function () {
            _vm.entries[0].requrchaseLevel = $('#requrchaseLevel').select2('data')[0]?.id;
        });

        // 初始化 销售品类
        let specLeveltype = await requestDict(DictionaryType.SPECLEVEL_TYPE);
        let specLevelremedyDate = specLeveltype.data;
        $('#specLevel')
            .empty()
            .select2({
                placeholder: '请选择销售品类...', //默认文字提示
                language: 'zh-CN', //汉化
                allowClear: true, //允许清空
                data: specLevelremedyDate.map((item) => {
                    return {
                        id: item.value,
                        text: item.displayName,
                    };
                }),
            });
        $('#specLevel').on('select2:select', function () {
            _vm.entries[0].specLevel = $('#specLevel').select2('data')[0]?.id;
        });

        if (isEdit) {
            $(`#requrchaseLevel`).val(_vm.entries[0].requrchaseLevel).trigger('change');
            $(`#specLevel`).val(_vm.entries[0].specLevel).trigger('change');
            let priceUnit = _vm.entries[0]?.isSettlementQty == true ? '元/头' : '元/kg';
            $('#priceUnit').text(`回购单价(${priceUnit})`);
        } else {
            let pigDefault = remedyDate.filter((item) => {
                return item.isDefault == true;
            });
            $(`#requrchaseLevel`).val(pigDefault[0]?.value).trigger('change');
            _vm.entries[0].requrchaseLevel = pigDefault[0]?.value;

            let specLevelDefault = remedyDate.filter((item) => {
                return item.isDefault == true;
            });
            $(`#specLevel`).val(specLevelDefault[0]?.value).trigger('change');
            _vm.entries[0].specLevel = specLevelDefault[0]?.value;
        }

        // 计算均重
        $('#weight,#count').on('change', function (e) {
            if (!isNaN(_vm.entries[0].weight) && !isNaN(_vm.entries[0].count) && Utils.IsNotNull(_vm.entries[0].weight) && Utils.IsNotNull(_vm.entries[0].count)) {
                _vm.entries[0].avgWeight = (_vm.entries[0].weight / _vm.entries[0].count).toFixed(2);
                _vm.entries[0].avgWeightShow = Utils.toThousands(_vm.entries[0].weight / _vm.entries[0].count, 2);
            } else {
                _vm.entries[0].avgWeight = 0;
                _vm.entries[0].avgWeightShow = 0;
            }
        });
        // 计算回购金额
        $(`#price,#isSettlementQty,#weight,#count`).on('change', () => {
            if (_vm.entries[0].isSettlementQty == true && !isNaN(_vm.entries[0].price) && !isNaN(_vm.entries[0].count)) {
                _vm.entries[0].amount = (_vm.entries[0].price * _vm.entries[0].count).toFixed(2);
                _vm.entries[0].amountShow = Utils.toThousands(_vm.entries[0].price * _vm.entries[0].count, 2);
            } else if (_vm.entries[0].isSettlementQty == false && !isNaN(_vm.entries[0].price) && !isNaN(_vm.entries[0].weight)) {
                _vm.entries[0].amount = (_vm.entries[0].price * _vm.entries[0].weight).toFixed(2);
                _vm.entries[0].amountShow = Utils.toThousands(_vm.entries[0].price * _vm.entries[0].weight, 2);
            } else {
                _vm.entries[0].amount = 0;
                _vm.entries[0].amountShow = 0;
            }
            let priceUnit = _vm.entries[0].isSettlementQty == true ? '元/头' : '元/kg';
            $('#priceUnit').text(`回购单价(${priceUnit})`);
        });
    };

    // 保存提示
    const savetips = (data) => {
        let saveEntry;
        if (Utils.IsNotNull(getUrlKey('operaEntryId'))) {
            savetype = '修改';
            saveEntry = getUrlKey('operaEntryId');
        } else {
            savetype = '保存';
            saveEntry = getUrlKey('nextEntryId');
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '保存',
                    onClick: function () {
                        let id = parseInt(getUrlKey('index'));
                        let isEdit = JSON.parse(getUrlKey('isEdit'));
                        // 新增
                        if (Utils.IsNotNull(getEntryInfo) && isEdit == false) {
                            getEntryInfo.push(data);
                        } else if (Utils.IsNotNull(getEntryInfo) && isEdit) {
                            // 编辑
                            getEntryInfo[id] = data;
                        } else {
                            getEntryInfo.push(data);
                        }
                        getEntryInfo.map((item, index) => {
                            item.id = index;
                        });
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));
                        location.href = `./addpigrepurchases.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    },
                },
            ],
        });
    };

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };
})(window, document, jQuery);
